# -*- coding: UTF-8 -*-
import MySQLdb
import hashlib
from config import Config
class Proxy_DbUtils:
    def __init__(self):
       config_db_proxy = Config('spider.conf')
       config_db_proxy.readDb()
       self.db = MySQLdb.connect(host=config_db_proxy.host, user=config_db_proxy.user, passwd=config_db_proxy.passwd, db=config_db_proxy.db_proxy,charset="utf8")

    def insert(self,url,content,flag,forward,praise,comment):
      ''' sql = "insert into c_data(url, \
              content, flag, forward, praise, comment) \
              values('%s', '%s', '%s', '%d', '%d', '%d' )" % \
             (url, content, flag, forward, praise, comment)
       cursor = self.db.cursor()

       # 执行sql语句
       cursor.execute(sql)
       # 提交到数据库执行
       self.db.commit()
       #except:
          # 发生错误时回滚
          #self.db.rollback()

        # 关闭数据库连接
       self.db.close()'''

    def close(self):
        self.db.close()

    def delete(self):
       '''sql = "delete from employee where age = '%d'" % (21)
       cursor = self.db.cursor()
       cursor.execute(sql)
       self.db.commit()
       self.db.close()'''

       print ''

    def update(self):
       '''sql = "update c_data set age = age + 1 where sex = '%c'" % ('M')
       cursor = self.db.cursor()
       cursor.execute(sql)
       self.db.commit()
       self.db.close()'''
       print ''

    def queryProxy(self):
       sql = "select ip,port from proxys where country = '国内' and score = 10"
       cursor = self.db.cursor()


       proxys = []
       try:
           # 执行SQL语句
           cursor.execute(sql)
           # 获取所有记录列表
           results = cursor.fetchall()
           for row in results:
               ip = row[0]
               port = row[1]
               proxy = [ip, port]
               proxys.append(proxy)
               #print 'ip = ' + str(ip) + "port = " + str(port)
       except Exception, e:
           print "Error: ", e
           print "Error: unable to fecth data"

       #print proxys
       return proxys
       self.db.close()


    def start(self):
        try:
            #DbUtils.create(self)
            #DbUtils.insert(self)
            #DbUtils.delete(self)
            #DbUtils.update(self)
            #DbUtils.query(self)
            Proxy_DbUtils.queryProxy(self)
        except Exception, e:
            print "Error: ", e

'''Proxy_DbUtils().start()

from spider import myproxy
i = 0

proxys = Proxy_DbUtils().queryProxy()
print proxys
ip = proxys[i][0]
port = proxys[i][1]
proxy = {
    'http': 'http://%s:%s' % (ip, port),
    'https': 'http://%s:%s' % (ip, port)
}
print proxy
while (myproxy().weibo_check(proxy) == False and i < 30):
    i += 1
    proxy = myproxy.getIp(i)
print myproxy().weibo_check(proxy)
print i'''